package ar.com.cooker.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import ar.com.cooker.dao.StepDao;
import ar.com.cooker.model.Recipe;
import ar.com.cooker.model.Step;

@Repository
@Transactional
public class StepDaoImpl implements StepDao {

	private EntityManager entityManager;
	
	@Override
	public void delete(Integer id) {
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Step> findAll() {
		return getEntityManager().createQuery("FROM Step").getResultList();
	}

	@Override
	public Step findById(Integer id) {
		return getEntityManager().find(Step.class, id);
	}

	@Override
	public void save(Step t) {
		getEntityManager().persist(t);
	}

	@Override
	public void update(Step t) {
		if(t.getId() == null){
			//excepsion
		}else{			
			getEntityManager().merge(t);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Step> findStepByRecipe(Integer idRecipe) {
		Recipe r = getEntityManager().find(Recipe.class, idRecipe);
		Query query = getEntityManager().createQuery("Select s " +
				"FROM Step s " +
				"WHERE s.recipe =:recipe").setParameter("recipe",r);
		return query.getResultList();
	}

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

}
